/*
 * @lc app=leetcode.cn id=874 lang=javascript
 *
 * [874] 模拟行走机器人
 */

// @lc code=start
/**
 * @param {number[]} commands
 * @param {number[][]} obstacles
 * @return {number}
 */
var robotSim = function (commands, obstacles) {
  let max = 0;
  let direction = 0;
  let pos = [0, 0];
  let map = {
    0: [0, 1],
    1: [1, 0],
    2: [0, -1],
    3: [-1, 0]
  };
  obstacles = obstacles.map(item => item + '');
  commands.forEach(command => {
    if (command === -2) {
      direction = (direction + 3) % 4;
    } else if (command === -1) {
      direction = (direction + 1) % 4;
    } else {
      const [difx, dify] = map[direction];
      for (let i = 0; i < command; i++) {
        let [x, y] = pos;
        x = x + difx;
        y = y + dify;
        if (obstacles.includes(`${x},${y}`)) {
          break;
        } else {
          pos = [x, y];
          max = Math.max(max, x * x + y * y)
        }
      }
    }
  });
  return max;
};
// @lc code=end
